package com.purong.purong.activity;

import android.content.Intent;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.PermissionConstant;
import com.purong.purong.R;
import com.purong.purong.adapter.CreditFyxxAdapter;
import com.purong.purong.adapter.CreditJbxxAdapter;
import com.purong.purong.adapter.CreditSkmjAdapter;
import com.purong.purong.adapter.CreditYhhdAdapter;
import com.purong.purong.adapter.CreditZstqAdapter;
import com.purong.purong.adapter.RecommCreditcardAdapter;
import com.purong.purong.bean.CreditCardBean;
import com.purong.purong.bean.CreditDetBean;
import com.purong.purong.bean.CreditDetBean.CreditDetItem;
import com.purong.purong.bean.CreditRecommBean;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.util.SharePreUtil;
import com.purong.purong.widget.FullyLinearLayoutManager;
import com.purong.purong.widget.LoadingView;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yao.sdk.glide.GlideUtil;
import com.yao.sdk.net.ResponseInfo;
import com.yaoming.umengshare.SharePlatform;
import com.yaoming.umengshare.UmShare;
import com.yaoming.umengshare.listener.ShareResultListener;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wenjiezeng on 2017/9/21.
 */
public class CreditDetialActivity extends BasePermActivity {
    private CreditCardBean credit;
    private LinearLayout tagLay;
    private ImageView creditImg,bklcImg,favoriteImg;
    private TextView name;
    private TextView outline;
    private RecyclerView zstqRecyView,jbxxRecyView,fyxxRecyView,yhhdRecyView,recommRecyView,skmjRecyView;
    private CreditZstqAdapter zstqAdapter;
    private CreditJbxxAdapter jbxxAdapter;
    private CreditFyxxAdapter fyxxAdapter;
    private CreditYhhdAdapter yhhdAdapter;
    private CreditSkmjAdapter skmjAdapter;
    private RecommCreditcardAdapter recommAdapter;
    private CreditDetBean bean;
//    private List<ArticleBean> articleList=new ArrayList<>();
    private List<CreditCardBean> recommList=new ArrayList<>();
    private LoadingView mLoadingView;
    private boolean needBack;
    @Override
    public void finish() {
        if (needBack&&bean!=null){
            Intent intent=new Intent();
            intent.putExtra("CREDIT",bean);
            setResult(RESULT_OK,intent);
        }
        super.finish();
    }
    @Override
    public void initBundle() {

        credit=(CreditCardBean)getIntent().getSerializableExtra("CREDIT");
        needBack=getIntent().getBooleanExtra("NEED_BACK",false);
    }

    @Override
    public int getRootViewId() {
        return R.layout.activity_credit_detial;
    }

    public void initView(){
        showBack();
        showTitle("信用卡详情");
        mLoadingView =(LoadingView)findViewById(R.id.loading_view);
        mLoadingView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                getDetial();
            }

            @Override
            public void onRefresh() {

            }
        });
        tagLay=(LinearLayout)findViewById(R.id.tag_lay);
        creditImg=(ImageView)findViewById(R.id.credit_img);
        int width= CommonUtil.getScreenWidth(this)-CommonUtil.dip2px(this,24);
        LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(width,(int)(width*0.569));
        lp.setMargins(CommonUtil.dip2px(this,12),CommonUtil.dip2px(this,12),CommonUtil.dip2px(this,12),CommonUtil.dip2px(this,20));
        creditImg.setLayoutParams(lp);
        name=(TextView)findViewById(R.id.credit_name);
        outline=(TextView)findViewById(R.id.credit_outline);
        zstqRecyView=(RecyclerView)findViewById(R.id.zstq_recycler_view);
        jbxxRecyView=(RecyclerView)findViewById(R.id.jbxx_recycler_view);
        fyxxRecyView=(RecyclerView)findViewById(R.id.fyxx_recycler_view);
        yhhdRecyView=(RecyclerView)findViewById(R.id.yhhd_recycler_view);
        skmjRecyView=(RecyclerView)findViewById(R.id.skmj_recycler_view);
        recommRecyView=(RecyclerView)findViewById(R.id.recomm_recycler_view);

        bklcImg=(ImageView)findViewById(R.id.bklc_img);
        favoriteImg=(ImageView)findViewById(R.id.favorite_img);
        int imgWidth=CommonUtil.getScreenWidth(this)-CommonUtil.dip2px(this,64);
        LinearLayout.LayoutParams lpImg=new LinearLayout.LayoutParams(imgWidth,(int)(imgWidth*0.174));
        lpImg.setMargins(CommonUtil.dip2px(this,32),CommonUtil.dip2px(this,24),CommonUtil.dip2px(this,24),CommonUtil.dip2px(this,32));
        bklcImg.setLayoutParams(lpImg);
        recommAdapter=new RecommCreditcardAdapter(this);
        recommAdapter.setData(recommList);
        recommAdapter.setOnCreditClickListener(new RecommCreditcardAdapter.OnCreditClickListener() {
            @Override
            public void onCreditClick(CreditCardBean card) {
                Intent intent=new Intent(CreditDetialActivity.this, CreditDetialActivity.class);
                intent.putExtra("CREDIT",card);
                startActivity(intent);
            }
        });
        recommRecyView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recommRecyView.setAdapter(recommAdapter);
    }

    @Override
    public void initData() {
        getDetial();
        getRecommCredit();
    }

    private void getDetial(){
        if (credit==null)
            return;
        mLoadingView.loading();
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("credit_id", credit.getCredit_product_id());
        if (!request(Contant.CREDIT_DETAILS, params, true, false)){
            mLoadingView.fail();
        }
    }
//    private void getArticle(){
//        if (credit==null)
//            return;
//        Map<String, String> params = new LinkedHashMap<String, String>();
//        params.put("category_code", "Strategy");
//        params.put("bank_id", credit.getBank_id());
//        request(Contant.ARTICLE_LIST, params, true, false);
//    }
    private void apply(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("credit_id",credit.getCredit_product_id());
        params.put("province_id", SharePreUtil.getInstance(this).getLoactionParentId());
        params.put("city_id",SharePreUtil.getInstance(this).getLoactionAreaId());
        request(Contant.CREDIT_APPLY, params, true, true);
    }
    private void setShare(String platform) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (platform.equals("WEIXIN")){
            params.put("share_type", "1");
        }else if (platform.equals("WEIXIN_CIRCLE")){
            params.put("share_type", "2");
        }else if (platform.equals("QQ")){
            params.put("share_type", "3");
        }
        params.put("credit_product_id", bean.getCredit_product_id());
        request(Contant.CREDIT_SHARE_LOG, params, true, false);
    }
    private void setFavourite(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("credit_id",credit.getCredit_product_id());
        request(Contant.CREDIT_FAVORITE, params, true, true);
    }
    private void cancelFavourite(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("credit_id",credit.getCredit_product_id());
        request(Contant.CREDIT_FAVORITE_CANCEL, params, true, true);
    }
    private void getRecommCredit(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("recommend_location","3");//【1：首页、2：信用卡主页推荐】
        params.put("city_id", SharePreUtil.getInstance(this).getLoactionAreaId());
        params.put("province_id", SharePreUtil.getInstance(this).getLoactionParentId());
        request(Contant.CREDIT_RECOMMEND, params, true, false);
    }
    private void setData(){
        GlideUtil.getInstance().load(this,bean.getCredit_product_url(),creditImg,true);
        name.setText(bean.getCredit_product_name());
        outline.setText(bean.getCredit_product_outline());
        if (bean.getIs_favorite().equals("1")){
            favoriteImg.setImageResource(R.drawable.cart_icon_collect);
        }else {
            favoriteImg.setImageResource(R.drawable.nav_icon_collect_sel);
        }
        setTag(bean.getCredit_tag_str());
        setZstq(bean.getCredit_privilege_str());
        setJbxx(bean.getCredit_base_str());
        setFyxx(bean.getCredit_fee_str());
        setYhhd(bean.getCredit_discount_str());
        setSkmj(bean.getCredit_cheat_str());


    }
    private void setZstq(List<CreditDetItem> itemList){
        if (itemList==null||itemList.size()==0){
            findViewById(R.id.zstq_lay).setVisibility(View.GONE);
            return;
        }else {
            findViewById(R.id.zstq_lay).setVisibility(View.VISIBLE);
        }
        zstqAdapter=new CreditZstqAdapter(this);
        zstqAdapter.setData(itemList);
        zstqRecyView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        zstqRecyView.setAdapter(zstqAdapter);
    }
    private void setJbxx(List<CreditDetItem> itemList){
        if (bean.getCredit_condition_str()!=null&&bean.getCredit_condition_str().size()!=0){
            bean.getCredit_condition_str().addAll(bean.getCredit_condition_str());
            CreditDetItem conditItem=new CreditDetBean().new CreditDetItem();
            conditItem.setTitle("申请条件");
            StringBuffer conditions=new StringBuffer();
            for (int i = 0; i <bean.getCredit_condition_str().size() ; i++) {
                conditions.append(bean.getCredit_condition_str().get(i));
                if (i!=bean.getCredit_condition_str().size()-1)
                    conditions.append("，");
            }
            conditItem.setContent(conditions.toString());
            itemList.add(conditItem);
        }
        if (itemList==null||itemList.size()==0){
            findViewById(R.id.jbxx_lay).setVisibility(View.GONE);
            return;
        }else {
            findViewById(R.id.jbxx_lay).setVisibility(View.VISIBLE);
        }
        jbxxAdapter=new CreditJbxxAdapter(this);
        jbxxAdapter.setData(itemList);
        jbxxRecyView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        jbxxRecyView.setAdapter(jbxxAdapter);
    }
    private void setSkmj(List<CreditDetItem> itemList){
        if (itemList==null||itemList.size()==0){
            findViewById(R.id.skmj_lay).setVisibility(View.GONE);
            return;
        }else {
            findViewById(R.id.skmj_lay).setVisibility(View.VISIBLE);
        }
        skmjAdapter=new CreditSkmjAdapter(this);
        skmjAdapter.setData(itemList);
        skmjRecyView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        skmjRecyView.setAdapter(skmjAdapter);
    }
    private void setFyxx(List<CreditDetItem> itemList){
        if (itemList==null||itemList.size()==0){
            findViewById(R.id.fyxx_lay).setVisibility(View.GONE);
            return;
        }else {
            findViewById(R.id.fyxx_lay).setVisibility(View.VISIBLE);
        }
        fyxxAdapter=new CreditFyxxAdapter(this);
        fyxxAdapter.setData(itemList);
        fyxxRecyView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        fyxxRecyView.setAdapter(fyxxAdapter);
    }
    private void setYhhd(List<CreditDetItem> itemList){
        if (itemList==null||itemList.size()==0){
            findViewById(R.id.yhhd_lay).setVisibility(View.GONE);
            return;
        }else {
            findViewById(R.id.yhhd_lay).setVisibility(View.VISIBLE);
        }
        yhhdAdapter=new CreditYhhdAdapter(this);
        yhhdAdapter.setData(itemList);
        yhhdRecyView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        yhhdRecyView.setAdapter(yhhdAdapter);
    }
    private void setTag(List<String> tagList){
        if (tagList==null)
            return;
        LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0,0,CommonUtil.dip2px(this,5),0);
        for (int i = 0; i <tagList.size() ; i++) {
            TextView tagTv=new TextView(this);
            tagTv.setBackgroundResource(R.drawable.blue_radius1_border);
            tagTv.setText(tagList.get(i));
            tagTv.setTextColor(getResources().getColor(R.color.blue));
            tagTv.setTextSize(10);
//            tagTv.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.text_min));
            tagTv.setLayoutParams(lp);
            tagTv.setPadding(CommonUtil.dip2px(this,3),CommonUtil.dip2px(this,3),CommonUtil.dip2px(this,3),CommonUtil.dip2px(this,3));
            tagLay.addView(tagTv);
        }
    }
    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.CREDIT_DETAILS)){
            if (responseInfo.isRequestOk){
                Log.e("zwj",responseInfo.content);
                try{
                    bean= JSON.parseObject(responseInfo.content,CreditDetBean.class);
                    if (bean!=null){
                        setData();
                        mLoadingView.finish();
                    }else {
                        mLoadingView.fail();
                    }

                }catch (Exception e){
                    mLoadingView.fail();
                }
            }else {
                mLoadingView.fail();
            }
        } else if (responseInfo.url.equals(Contant.CREDIT_RECOMMEND)){
            if (responseInfo.isRequestOk){
                try {
                    CreditRecommBean bean=JSON.parseObject(responseInfo.content,CreditRecommBean.class);
                    if (bean!=null&&bean.getCredit_recommend_list()!=null&&bean.getCredit_recommend_list().size()>0){
                        recommList.clear();
                        if (bean.getCredit_recommend_list().size()>4){
                            recommList.addAll(bean.getCredit_recommend_list().subList(0,4));
                        }else {
                            recommList.addAll(bean.getCredit_recommend_list());
                        }
                        recommAdapter.notifyDataSetChanged();
                        findViewById(R.id.wntj_lay).setVisibility(View.VISIBLE);
                    }
                }catch (Exception e){

                }
            }
        }else if (responseInfo.url.equals(Contant.CREDIT_APPLY)){
            if (responseInfo.isRequestOk){
                Intent intent=new Intent(this,WebActivity.class);
                intent.putExtra("TITLE", "申请信用卡");
                intent.putExtra("URL", bean.getCredit_apply_url());
                intent.putExtra("TITLEBAR", true);
                startActivity(intent);
            }
        }else if (responseInfo.url.equals(Contant.CREDIT_FAVORITE)){
            if (responseInfo.isRequestOk){
                showToast("已收藏");
                favoriteImg.setImageResource(R.drawable.nav_icon_collect_sel);
                bean.setIs_favorite("2");
            }
        }else if (responseInfo.url.equals(Contant.CREDIT_FAVORITE_CANCEL)){
            if (responseInfo.isRequestOk){
                showToast("已取消收藏");
                favoriteImg.setImageResource(R.drawable.cart_icon_collect);
                bean.setIs_favorite("1");
            }
        }
    }

    public void onClick(View v){
        if (bean==null)
            return;
        switch (v.getId()){
            case R.id.share:
                if (Build.VERSION.SDK_INT >= 23) {
                    checkPermission();
                } else {
                    share();
                }

                break;
            case R.id.favorite:
                if (bean.getIs_favorite().equals("1")){
                    setFavourite();
                }else {
                    cancelFavourite();
                }
//
                break;
            case R.id.fyxx_detial:
                if (bean.getCredit_fee_str()!=null){
                    Intent intent=new Intent(this,CreditItemDetActivity.class);
                    intent.putExtra("TITLE","费用信息");
                    intent.putExtra("ITEM_LIST",bean.getCredit_fee_str());
                    if (bean.getCredit_interest_str()!=null){
                        intent.putExtra("INTEREST_LIST",bean.getCredit_interest_str());
                    }
                    startActivity(intent);

                }
                break;
            case R.id.yhhd_detial:
                if (bean.getCredit_discount_str()!=null){
                    Intent intent=new Intent(this,CreditItemDetActivity.class);
                    intent.putExtra("TITLE","优惠活动");
                    intent.putExtra("ITEM_LIST",bean.getCredit_discount_str());
                    startActivity(intent);

                }
                break;
            case R.id.zstq_detial:
                if (bean.getCredit_privilege_str()!=null){
                    Intent intent=new Intent(this,CreditItemDetActivity.class);
                    intent.putExtra("TITLE","专属特权");
                    intent.putExtra("ITEM_LIST",bean.getCredit_privilege_str());
                    startActivity(intent);

                }
                break;
            case R.id.apply:

                apply();

                break;
        }
    }
    private void share(){
        UmShare share = new UmShare(this, new ShareResultListener() {
            @Override
            public void onStart(String platform) {
                setShare(platform);
            }

            @Override
            public void onSuccess(String platform) {
            }

            @Override
            public void onCancel(String platform) {
            }

            @Override
            public void onError(String platform, Throwable t) {
            }
        });
        if (bean.getCredit_product_url()!=null&&!bean.getCredit_product_url().equals("")){
            share.setImage(bean.getCredit_product_url());
        }else {
            share.setImage(R.mipmap.app_icon);
        }
        share.setText("普融—网申信用卡到普融，方便快捷，坐等收卡。");
        share.setTitle("普融—中国中小企业普惠金融O2O模式领导者");
        if (bean.getShare_url()!=null&&bean.getShare_url().startsWith("http")){
            share.setTargetUrl(bean.getShare_url());
        }else {
            share.setTargetUrl("http://www.purong.com/");
        }
        share.setPlatform(new SharePlatform(SHARE_MEDIA.WEIXIN),new SharePlatform(SHARE_MEDIA.WEIXIN_CIRCLE),new SharePlatform(SHARE_MEDIA.QQ));
        share.share();
    }
    @Override
    protected String[] getPermissions() {
        return PermissionConstant.PERMS_STORAGE;
    }

    @Override
    protected void doPermissinosSuc() {
        share();
    }
}
